package basemodel

import (
	"database/sql/driver"
	"fmt"
	"strings"
	"time"
)

type LocalTime struct {
	time.Time
}

func NewLocalTime(time time.Time) *LocalTime {
	return &LocalTime{Time: time}
}

type IchubLocalTime time.Time

func (t *LocalTime) MarshalJSON() ([]byte, error) {
	//格式化秒seconds := t.Unix() return []byte(strconv.FormatInt(seconds, 10)), nil
	tune := t.Format("20060102150405")
	return []byte(tune), nil
}

func (t *LocalTime) UnmarshalJSON(data []byte) error {
	if string(data) == "null" {
		return nil
	}
	//var err error
	//前端接收的时间字符串
	str := string(data)
	//去除接收的str收尾多余的"
	timeStr := strings.Trim(str, "\"")
	t1, err := time.Parse("20060102150405", timeStr)
	t.Time = t1
	return err
}

func (t *LocalTime) Value() (driver.Value, error) {
	var zeroTime time.Time
	if t.Time.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return t.Time, nil
}
func (t *LocalTime) Scan(v interface{}) error {
	value, ok := v.(time.Time)
	if ok {
		*t = LocalTime{Time: value}
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}

func (t *LocalTime) FormatDatetime() string {
	return t.Time.Format("2006-01-02 15:04:05")
}
